//
//  SelectFactoryViewController.m
//  MagictoLane
//
//  Created by 锋 on 2018/1/2.
//  Copyright © 2018年 HUAYU. All rights reserved.
//

#import "SelectFactoryViewController.h"
#import "SelectFactoryTableViewCell.h"
#import "SelectFactoryModel.h"

@interface SelectFactoryViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UITextFieldDelegate>
@property (nonatomic, strong) UITableView *selectFactoryTableView;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSMutableArray *selectFactoryArr;
@property (nonatomic, strong) NSMutableArray *filterArray;
@property (nonatomic, strong) NSMutableArray *whichFactoryArr;
@property (nonatomic, strong) NSString *searchString;
@end

@implementation SelectFactoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _page = 0;
    
    _selectFactoryArr = @[].mutableCopy;
    _filterArray = @[].mutableCopy;
    _whichFactoryArr = @[].mutableCopy;
    [self setupUI];
    [self setupSelectFactoryTableView];
    [self requestFactoryList];
    // Do any additional setup after loading the view.
}

- (void)setupUI {
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"确认" style:UIBarButtonItemStylePlain target:self action:@selector(onClickEnsure)];
    [rightBtn setTintColor:[UIColor whiteColor]];
    [rightBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], UITextAttributeFont,nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = rightBtn;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"选择工厂";
    self.view.backgroundColor = RGB(242, 242, 242);
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];
}

- (void)keyboardHide:(UITapGestureRecognizer *)tap {
    [self.view endEditing:YES];
}
- (void)setupSelectFactoryTableView {
    _selectFactoryTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STA_NAV_HEIGHT - SCREER_HeiX) style:UITableViewStyleGrouped];
    _selectFactoryTableView.delegate = self;
    _selectFactoryTableView.dataSource = self;
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45)];
    headerView.backgroundColor = [UIColor whiteColor];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.00001)];
    view.backgroundColor = [UIColor whiteColor];
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45)];
    _searchBar.backgroundColor = [UIColor whiteColor];
    _searchBar.delegate = self;
    [headerView addSubview:_searchBar];
    _selectFactoryTableView.tableHeaderView = headerView;
    _selectFactoryTableView.tableFooterView = view;
    self.selectFactoryTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    self.selectFactoryTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFootData)];
    self.selectFactoryTableView.mj_footer.automaticallyHidden = YES;
    self.selectFactoryTableView.estimatedRowHeight = 0;
    self.selectFactoryTableView.estimatedSectionHeaderHeight = 0;
    self.selectFactoryTableView.estimatedSectionFooterHeight = 0;
    _selectFactoryTableView.backgroundColor = RGB(242, 242, 242);
    if (@available(iOS 11.0, *)) {
        _selectFactoryTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    _selectFactoryTableView.estimatedRowHeight = 0;
    _selectFactoryTableView.estimatedSectionHeaderHeight = 0;
    _selectFactoryTableView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:_selectFactoryTableView];
}

- (void)loadNewHeaderData {
    _page = 0;
    if (_filterArray && _filterArray.count > 0) {
        [self requestSearchFactoryList:_searchString];
    } else {
        [self requestFactoryList];
    }
}

- (void)loadMoreFootData {
    _page++;
    if (_filterArray && _filterArray.count > 0) {
        [self requestSearchFactoryList:_searchString];
    } else {
        [self requestFactoryList];
    }
}

- (void)requestFactoryList {
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestContactorMatchListParmers:@{@"projectId" : _projectId, @"page" : [NSString stringWithFormat:@"%ld", _page]} Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [weakSelf.selectFactoryTableView.mj_header endRefreshing];
         [weakSelf.selectFactoryTableView.mj_footer endRefreshing];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             NSArray *tempArray = [SelectFactoryModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
             if (weakSelf.page == 0)
             {
                 [weakSelf.selectFactoryArr removeAllObjects];
             }
             [weakSelf.selectFactoryArr addObjectsFromArray:tempArray];
             [_selectFactoryTableView reloadData];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [weakSelf.selectFactoryTableView.mj_header endRefreshing];
         [weakSelf.selectFactoryTableView.mj_footer endRefreshing];
     }];
}

- (void)requestSearchFactoryList:(NSString *)searchStr {
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestSearchContactorMatchListParmers:@{@"projectId" : _projectId, @"page" : [NSString stringWithFormat:@"%ld", _page], @"query":searchStr} Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [weakSelf.selectFactoryTableView.mj_header endRefreshing];
         [weakSelf.selectFactoryTableView.mj_footer endRefreshing];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             NSArray *tempArray = [SelectFactoryModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
             if (weakSelf.page == 0)
             {
                 [weakSelf.filterArray removeAllObjects];
             }
             [weakSelf.filterArray addObjectsFromArray:tempArray];
             [_selectFactoryTableView reloadData];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [weakSelf.selectFactoryTableView.mj_header endRefreshing];
         [weakSelf.selectFactoryTableView.mj_footer endRefreshing];
     }];
}

- (void)onClickEnsure {
    WEAKSELF;
    NSMutableArray *contractorIdArr = @[].mutableCopy;
    if (_whichFactoryArr.count > 0) {
        for (int i = 0; i < _whichFactoryArr.count; i++) {
            NSInteger index = [_whichFactoryArr[i] integerValue];
            SelectFactoryModel *model;
            if (_filterArray && _filterArray.count > 0) {
                model = _filterArray[index];
            } else {
                model = _selectFactoryArr[index];
            }
            [contractorIdArr addObject:model.ID];
        }
    } else {
        [LTools showMBProgressWithText:@"请选择工厂" addToView:weakSelf.view];
        return;
    }
    NSSet *set = [NSSet setWithArray:contractorIdArr];
    [contractorIdArr removeAllObjects];
    contractorIdArr = [NSMutableArray arrayWithArray:[set allObjects]];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestContactorEnsureParmers:@{@"projectId" : _projectId, @"contractorIds" : contractorIdArr} Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             [LTools showMBProgressWithText:@"提交成功" addToView:weakSelf.view];
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [self.navigationController popToRootViewControllerAnimated:YES];
             });
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         
     }];
}

// MARK:tableview的方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_filterArray && _filterArray.count > 0) {
        return _filterArray.count;
    } else {
        return _selectFactoryArr.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 125;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectFactoryTableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:@"SelectFactoryTableViewCell" owner:self options:nil].lastObject;
    cell.layer.cornerRadius = 5;
    cell.layer.masksToBounds = YES;
    cell.selectBtn.tag = indexPath.section;
    [cell.selectBtn addTarget:self action:@selector(onClickStatusBtn:) forControlEvents:UIControlEventTouchUpInside];
    SelectFactoryModel *model;
    if (_filterArray && _filterArray.count > 0) {
        model = _filterArray[indexPath.section];
    } else {
        model = _selectFactoryArr[indexPath.section];
    }
    [cell.factoryImageView sd_setImageWithURL:[NSURL URLWithString:model.user.headImg] placeholderImage:nil];
    cell.fatoryNameLabel.text = model.user.name;
    cell.fatoryAddressLabel.text = model.address;
    cell.billNumberLabel.text = model.user.finishCount;
    cell.gradeLabel.text = model.user.grade;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectFactoryTableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.section]];
    [self onClickStatusBtn:cell.selectBtn];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)onClickStatusBtn:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [_whichFactoryArr addObject:[NSString stringWithFormat:@"%ld", sender.tag]];
    } else {
        for (int i = 0; i < _whichFactoryArr.count; i++) {
            NSInteger index = [_whichFactoryArr[i] integerValue];
            if (index == sender.tag) {
                [_whichFactoryArr removeObjectAtIndex:i];
            }
        }
    }
}

//MARK: 搜索方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    _searchString = searchText;
    [self.whichFactoryArr removeAllObjects];
    [self.filterArray removeAllObjects];   //过去数据全部消除
    
//    for (int i = 0; i < self.selectFactoryArr.count; i++) {
//        SelectFactoryModel *model = _selectFactoryArr[i];
//
//        if ([model.user.name containsString:self.searchBar.text]) {
//            [self.filterArray addObject:model];
//        }
//    }
    if ([searchText isEqual:@""]) {
        [self requestFactoryList];
    } else {
        [self requestSearchFactoryList:searchText];
    }
    
//    [self.selectFactoryTableView reloadData];
    //    [self.areaListTableView reloadData];    //重置TableView
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    [_searchBar resignFirstResponder];
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [_searchBar resignFirstResponder];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    /* 防止错乱停止编辑*/
    [self.searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
